package com.teaRestaurant.controller.admin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.teaRestaurant.common.properties.JwtProperties;
import com.teaRestaurant.common.result.Result;
import com.teaRestaurant.domain.DTO.EmployeeLoginDTO;
import com.teaRestaurant.domain.DTO.EmployeePageQueryDTO;
import com.teaRestaurant.domain.VO.EmployeeLoginVO;
import com.teaRestaurant.domain.VO.EmployeePageQueryVO;
import com.teaRestaurant.domain.entity.Employee;
import com.teaRestaurant.service.EmployeeService;
import com.teaRestaurant.common.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin/employee")
@Slf4j
@Api(tags = "员工相关接口")
@CrossOrigin
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private JwtProperties jwtProperties;
    @PostMapping("/login")
    @ApiOperation("员工登录")
    public Result<EmployeeLoginVO> login (@RequestBody EmployeeLoginDTO employeeLoginDTO) {

        EmployeeLoginVO employeeLoginVO = employeeService.login(employeeLoginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("empId", employeeLoginVO.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);
        employeeLoginVO.setToken(token);

        return Result.success(employeeLoginVO);
    }

    /**
     * 获取员工列表
     */
    @GetMapping
    public Result list (EmployeePageQueryDTO employeePageQueryDTO) {
        IPage<EmployeePageQueryVO> employeeList = employeeService.list(employeePageQueryDTO);
        return Result.success(employeeList);
    }

    /**
     * 新增员工
     * 新增信息：名字，手机号，性别
     */
    @PostMapping
    public Result insert (@RequestBody Employee employee) {
        employeeService.insert(employee);
        return Result.success();
    }

    /**
     * 删除员工
     */
    @DeleteMapping
    public Result delete (@RequestParam String ids) {
        System.out.println(ids);
        List <Long> ids2 = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
        employeeService.delete(ids2);
        return Result.success();
    }

    /** 更新员工状态
     *
     */
    @PutMapping("/updateStatus/{id}")
    public Result updateStatus (@PathVariable("id") Long id) {
        employeeService.updateStatus(id);
        return Result.success();
    }

}
